#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json
import enum



class DiffLineType(enum.IntEnum):
    added = 1,
    removed = 2,
    untouched = 3,
    meta = 4,

def text_changes(value):
    value_data = value.splitlines()
    result = []
    for line in value_data:
        line_type = DiffLineType.untouched
        if line.startswith('+ '):
            line_type = DiffLineType.added
        elif line.startswith('- '):
            line_type = DiffLineType.removed
        elif line.startswith('? '):
            line_type = DiffLineType.meta
        result.append( [line_type, line] )
    return result


def diff_to_json(value):
    return json.dumps(value, indent=2)

def json_to_diff(value, enum_type=None):
    result = json.loads(value)

    # Перевод строчных ключей в целочисленные
    def _keys_to_int(container):
        result = {}
        for key, value in container.items():
            if dict == type(value):
                value = _keys_to_int(value)
            result[int(key)] = value
        return result
    result = _keys_to_int(result)

    if enum_type == None:
        return result

    # Типизация ключей первого уровня по enum_type
    for key in enum_type:
        json_key = int(key)
        if json_key in result:
            result[key] = result.pop(json_key)
    return result
